﻿using System;
using System.Data.SqlClient;

namespace MyFloridaHouse.DataAccess
{
	//Todo: Unused code never referenced.
	/// <summary>
	/// Data Aaccess Layer Census Data methods for SQL Azure applications
	/// </summary>
    public partial class DAL_CensusData
    {
        //From online documentation
        // http://msdn.microsoft.com/en-us/library/ff394106.aspx
        // This topic contains information about errors that can occur only when using Microsoft SQL Azure Database.
        
        //We recommend that you implement the retry logic in your SQL Azure applications to catch 
        //these errors. When an error occurs, re-establish the connection and then re-execute the 
        //failed commands or the query.         

        //When your connection to the service is closed, you will receive one of the following errors: 
        //40197, 40501, 40544, 40549, 40550, 40551, 40552, 40553, and 40613. 



		/// <summary>
		/// max Retry Attempts
		/// </summary>
        const int maxRetryAttempts = 3;

		/// <summary>
		/// Retries the Azure SQL connection failures.
		/// </summary>
		/// <typeparam name="R"></typeparam>
		/// <param name="func">The func.</param>
		/// <returns></returns>
        protected R RetryConnectionFailures<R>(Func<R> func)
        {
            var tries = 0;

            while (true)
            {
                try
                {
                    R result = func();
                    return result;
                }
                catch (SqlException e)
                {
                    if (e.Number != -2)
                    {
                        throw;
                    }

                    if (tries++ == maxRetryAttempts)
                    {
                        throw;
                    }
                }
            }
        }

    }
}
